package com.shanglv.web.common.directive;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.util.Map;

public class OverrideDirective extends BaseDirective implements TemplateDirectiveModel {

    public static final String OVERRIDE_VAR_PREFIX = "OVERRIDE_TAG";

    @Override
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {

        String name = getParams(params, ATTR_NAME);
        boolean addendValue = (getParams(params, APPEND_NAME) != null);
        if (StringUtils.isNotBlank(name)) {
            String tagName = OVERRIDE_VAR_PREFIX+name;
            env.setVariable(tagName,new TemplateBodyModel(tagName,body,addendValue));
        }
    }
}
